<template>
  <el-dialog :title="'修改密码'" v-model="visible" width="420px" @close="handleClose">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" status-icon>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入新密码" />
      </el-form-item>
      <el-form-item label="验证码" prop="captchaInput">
        <div style="display:flex;align-items:center;gap:8px;">
          <el-input v-model="form.captchaInput" placeholder="输入验证码" style="flex:1" />
          <img :src="captchaImage" @click="refreshCaptcha" title="点击刷新验证码" style="height:38px;cursor:pointer;border:1px solid #e6e6e6;padding:2px;background:#fff" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="onSubmit">确认修改</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { generateCaptcha } from '@/utils/captcha'

const props = defineProps({
  visible: Boolean,
  adminId: [Number, String]
})
const emit = defineEmits(['update:visible', 'success'])

const visible = ref(props.visible)

const resetForm = () => {
  form.password = ''
  form.confirmPassword = ''
  form.captchaInput = ''
  // reset validation state if formRef available
  if (formRef.value && formRef.value.resetFields) {
    try {
      formRef.value.resetFields()
    } catch (e) {
      // ignore
    }
  }
}

// 当父组件控制 visible 变化时，同步并在打开时重置表单与验证码
watch(() => props.visible, v => {
  visible.value = v
  if (v) {
    resetForm()
    refreshCaptcha()
  }
})
watch(visible, v => emit('update:visible', v))

const formRef = ref()
const form = reactive({
  password: '',
  confirmPassword: '',
  captchaInput: ''
})

const rules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度 6-20 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value !== form.password) callback(new Error('两次输入的密码不一致'))
      else callback()
    }, trigger: 'blur' }
  ],
  captchaInput: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

const captchaImage = ref('')
let currentCode = ''

const refreshCaptcha = () => {
  const r = generateCaptcha(120, 40, 5)
  captchaImage.value = r.dataUrl
  currentCode = r.code
}

onMounted(() => {
  refreshCaptcha()
})

const handleClose = () => {
  emit('update:visible', false)
}

const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    // 验证码校验
    if (form.captchaInput.toLowerCase() !== currentCode.toLowerCase()) {
      ElMessage.error('验证码错误，请重试')
      refreshCaptcha()
      return
    }

    try {
      // 二次确认
      await ElMessageBox.confirm('确认要修改该管理员的密码吗？修改后请通知管理员使用新密码登录。', '请确认', {
        confirmButtonText: '确认修改',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // emit success 交由上层组件调用 API
      emit('success', { password: form.password })
    } catch (e) {
      // 用户取消
    }
  })
}
</script>
